<template>
  <!-- 下拉刷新组件 -->
  <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
    <van-list
      v-model:loading="listLoading"
      :finished="listFinished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <div class="container">
        <!-- 左列 -->
        <div class="list-container">
          <div
            class="list-item"
            v-for="(item, index) in leftList"
            :key="item.item_id"
          >
            <find-list-item
              :Item="item"
              :index="index"
              @giveLike="toggleLike(item)"
            ></find-list-item>
          </div>
        </div>
        <!-- 右列 -->
        <div class="list-container">
          <div class="list-item" v-for="item in rightList" :key="item.item_id">
            <find-list-item
              :Item="item"
              @giveLike="toggleLike(item)"
            ></find-list-item>
          </div>
        </div>
      </div>
    </van-list>
  </van-pull-refresh>
</template>

<script setup>
import { ref, onActivated, onMounted } from "vue";
import { useRouter, onBeforeRouteLeave, useRoute } from "vue-router";
import { List as VanList, PullRefresh as VanPullRefresh, Toast } from "vant";
import { cancelPromise } from "@/utils/cancelPromise";
import { getFindList } from "@/api/FindModuleAPI/findList.js";
import { getLikeForFind, clickLike } from "@/api/FindModuleAPI/findLike.js";
import { showStatusTip } from "@/utils/loginStatus";
import { LRU } from "@/utils/LRU.js";
import FindListItem from "./FindListItem.vue";

// 父组件的传参
const props = defineProps({
  // 发现的标签
  findType: {
    type: String,
    default: () => "",
  },
  // 是否是我的发现
  ismine: {
    type: Boolean,
    default: () => false,
  },
});

// 列表加载
let listLoading = ref(true);
// 列表完成
let listFinished = ref(false);
// 下拉刷新
let refreshing = ref(false);
// item列表
let leftList = ref([]);
let rightList = ref([]);
// 左右高度
let leftHeight = 0;
let rightHeight = 0;
// 每页个数
let limit = 5;
// 当前页数
let page = 0;
// 总页数
let allPage = -1;
// 用于组件再次激活时执行未完成的操作
let curfun = {};
// 路由缓存滚动定位
let scrollTop = 0;
// 非响应式搜索值（父组件可传入）
let search = "";
let loadTime = Date.now();

//最后一次点击进入的详情页id，同步点赞功能
let lastClickId = "";

//LRU算法
let LRUMap = null;
onMounted(() => {
  LRUMap = new LRU(10);
});

const router = useRouter();
const route = useRoute();


//更新列表页中对应详情页的点赞信息
const updateBackLike = async () => {
  if (!lastClickId) return;
  let flag = false;
  let changeInfo = LRUMap.get(lastClickId);

  if (!changeInfo) {
    //遍历左列表
    for (let i = 0; i < leftList.value.length; i++) {
      if (leftList.value[i].item_id == lastClickId) {
        changeInfo = leftList.value[i];
        flag = true;
        break;
      }
    }
    //遍历右列表
    for (let i = 0; i < rightList.value.length && !flag; i++) {
      if (rightList.value[i].item_id == lastClickId) {
        changeInfo = rightList.value[i];
        flag = true;
        break;
      }
    }
    if (!changeInfo) return;
    LRUMap.set(lastClickId,changeInfo);
  }

  //请求后端更新点赞数
  let params = {
    post_id: lastClickId,
    username: sessionStorage.getItem("username"),
  };
  const res = await getLikeForFind(params);
  if (res.success) {
    changeInfo.likeNum = res.likeNum;
    changeInfo.isLike = res.isLike;
  }
  lastClickId = "";
};

// 组件激活
onActivated(() => {
  updateBackLike();
  document.documentElement.scrollTop = scrollTop;
});

// 存储路由滚动位以及相应的详情页信息
onBeforeRouteLeave((to, from) => {
  scrollTop = document.documentElement.scrollTop;
  if (to.name == "videoDetail" || to.name == "articleDetail") {
    lastClickId = to.params.id;
  }
});

// 搜索事件
const onSearch = (searchValue) => {
  search = searchValue;
  refreshing.value = true;
  onRefresh();
};

// 列表加载事件
const onLoad = () => {
  // 刷新
  if (refreshing.value) {
    page = 0;
    allPage = -1;
    leftList.value = [];
    rightList.value = [];
    leftHeight = 0;
    rightHeight = 0;
    refreshing.value = false;
  }
  // 加载
  // 不是最后一页
  if (page !== allPage) {
    renderList(search);
  }
  // 最后一页
  else {
    listFinished.value = true;
    listLoading.value = false;
  }
};

// 列表下拉刷新事件（暴露出加载事件以实现懒加载）
const onRefresh = () => {
  loadTime = Date.now();
  listFinished.value = false;
  listLoading.value = true;
  onLoad();
};

// 点赞与取消
const toggleLike = async (item) => {
  // 游客用户无法点赞
  if (sessionStorage.getItem("visitor") === "true") {
    showStatusTip(() => {}, "，无法点赞哦！");
    return;
  }
  //未审核用户无法点赞
  if (item.status !== 1) return;

  const toast1 = Toast.loading({
    duration: 0,
    forbidClick: true,
    message: "点赞中...",
    onOpened: async () => {
      let res = await cancelPromise.throttle(
        clickLike({
          id: item.item_id,
          username: sessionStorage.getItem("username"),
        })
      );
      if (!res) return;
      if (res.success) {
        item.likeNum = res.likeNum;
        item.isLike = res.isLike;
        toast1.clear();
        Toast.success({
          message: item.isLike ? "点赞成功♥" : "取消点赞!",
          forbidClick: true,
          duration: 200,
        });
      }
    },
  });
};

// 列表渲染
const renderList = (keywords) => {
  const { ismine, findType } = props;
  curfun = function () {
    return getFindList({
      limit,
      page: page + 1,
      username: sessionStorage.getItem("username") || "",
      keywords,
      ismine,
      findType,
      loadTime,
    })
      .then((res) => {
        listLoading.value = false;
        LRUMap.reset();
        allPage = res.allPage;
        page++;
        // 解决当没有搜索结果时的bug
        if (allPage === 0) {
          page--;
        }
        for (const item of res.list) {
          const flag = leftHeight > rightHeight;
          if (flag) {
            rightList.value.push(item);
            LRUMap.set(item.item_id,item)
            rightHeight += imageHeight(item);
          } else {
            leftList.value.push(item);
            LRUMap.set(item.item_id,item)
            leftHeight += imageHeight(item);
          }
        }

      })
      .catch((err) => {});
  };
  cancelPromise.debounce(findType, curfun);
};
// 计算每个容器高度
const imageHeight = (item) => {
  // 比例
  const ratio = document.documentElement.clientWidth / 2 / item.width;
  // 计算高度
  item.height = Math.ceil(item.height * ratio);
  const result = item.height + 105;
  return item.height > 400 ? 400 : result;
};
// 将列表所需数据置空
const setInit = () => {
  page = 0;
  allPage = -1;
  leftList.value = [];
  rightList.value = [];
  leftHeight = 0;
  rightHeight = 0;
  listFinished.value = false;
  listLoading.value = true;
  search = "";
  renderList(search);
};

// 组件对外接口
defineExpose({
  onSearch,
  setInit,
  onRefresh,
});
</script>

<style lang="less" scoped >
// 头部标签
:deep(.van-tab) {
  font-weight: 500;
  border: 2px solid #fff;
}
:deep(.van-tabs__line) {
  background: #4389fc;
}
// 列表底部显示
:deep(.van-list) {
  padding-bottom: 50px;
}
// 判断发现状态
.pending {
  margin-right: 3px;
}
// 列表容器（两列）
.list-container {
  width: 49%;
  .list-item {
    break-inside: avoid;
    background-color: #fff;
    border-radius: 5px;
    box-shadow: 0 2px 5px #858585;
    margin-bottom: 8px;
    padding-bottom: 5px;
    overflow: hidden;
    .list-content {
      position: relative;
      .list-item-detail {
        .cover {
          opacity: 0;
          transition: all 0.5s;
          -moz-transition: all 0.5s; /* Firefox 4 */
          -webkit-transition: all 0.5s; /* Safari 和 Chrome */
          -o-transition: all 0.5s; /* Opera */
          max-height: 400px;
        }
        .list-item-detail-title {
          white-space: normal;
          word-break: break-all;
          margin: 0 10px;
          padding-top: 5px;
          margin-bottom: 10px;
          font-size: 14px;
          text-align: left;
          font-weight: 600;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          overflow: hidden;
          height: 40px;
          line-height: 20px;
        }
        .list-item-detail-footer {
          padding: 5px 5px 5px 0;
          display: flex;
          justify-content: space-between;
          .list-item-detail-footer-left {
            display: flex;
            align-items: center;
            div {
              margin-left: 5px;
              font-size: 12px;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
              width: 60px;
              text-align: left;
            }
          }
          .list-item-detail-footer-right {
            display: flex;
            align-items: center;
            span {
              padding-left: 2px;
              font-size: 12px;
              white-space: nowrap;
            }
          }
        }
      }
    }
  }
}
// 错位布局容器
.container {
  display: flex;
  width: 98%;
  margin: 5px auto 0;
  justify-content: space-between;
}
</style>
